package com.group1.ws;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.hibernate.Session;

import com.group1.model.AnswerItem;
import com.group1.model.Question;
import com.group1.model.QuestionImage;
import com.group1.util.SessionFactoryUtil;
import com.sun.jersey.core.header.FormDataContentDisposition;
import com.sun.jersey.multipart.FormDataParam;

@Path("/questionImage")
public class QuestionImageWS {
	
	@GET
	@Path("/getAll")
	@Produces(MediaType.TEXT_PLAIN)
	public String getAllQuestionImage(){
		Session session = SessionFactoryUtil.getSessionFactory().getCurrentSession();
		 session.beginTransaction();
		List<QuestionImage> list = QuestionImage.getAllQuestImg(session);
		String result;
		result = "{QUESTION_IMG:[";
		boolean first = true;
		for (QuestionImage q : list) {
			Integer questImgID = q.getQuestimId();
			Integer questID = q.getQuestion().getQuestionId();
			Integer answerID = q.getAnswerItem().getAnsiId();
			String questImgLink = q.getQuestimLink();
			result += (first?"":",");
			result += "{";
			first = false;
			result += "\"questImgID\"" + ":\"" + questImgID + "\",";
			result += "\"questID\"" + ":\"" + questID + "\",";
			result += "\"answerID\"" + ":\"" + answerID + "\",";
			result += "\"questImgLink\"" + ":\"" + questImgLink + "\",";
			result += "}";
		}
		result += "]}";
		session.getTransaction().commit();
		return result;
	}
	
	@GET
	@Path("/getByID/{questImgID}")
	@Produces(MediaType.TEXT_PLAIN)
	public String getQuestionImgByID(@PathParam("questImgID") String questImgID){
		Session session = SessionFactoryUtil.getSessionFactory().getCurrentSession();
		 session.beginTransaction();
		 QuestionImage q = QuestionImage.getQuestImgByID(Integer.valueOf(questImgID), session);
		String result;
		result = "{QUESTION_IMG:{";
		result += "\"questImgID\"" + ":\"" + questImgID + "\",";
		result += "\"questID\"" + ":\"" + q.getQuestion().getQuestionId() + "\",";
		result += "\"answerID\"" + ":\"" + q.getAnswerItem().getAnsiId() + "\",";
		result += "\"questImgLink\"" + ":\"" + q.getQuestimLink() + "\",";
		result += "}}";
		session.getTransaction().commit();
		return result;
	}
	@GET
	@Path("/getByQuestion/{questID}")
	@Produces(MediaType.TEXT_PLAIN)
	public String getQuestionImgQuestion(@PathParam("questID") String questID){
		Session session = SessionFactoryUtil.getSessionFactory().getCurrentSession();
		 session.beginTransaction();
		List<QuestionImage> list = QuestionImage.getImgOfQuestion(Integer.valueOf(questID), session);
		String result;
		result = "{QUESTION_IMG:[";
		boolean first = true;
		for (QuestionImage q : list) {
			Integer questImgID = q.getQuestimId();
			Integer answerID = q.getAnswerItem().getAnsiId();
			String questImgLink = q.getQuestimLink();
			result += (first?"":",");
			result += "{";
			first = false;
			result += "\"questImgID\"" + ":\"" + questImgID + "\",";
			result += "\"questID\"" + ":\"" + questID + "\",";
			result += "\"answerID\"" + ":\"" + answerID + "\",";
			result += "\"questImgLink\"" + ":\"" + questImgLink + "\",";
			result += "}";
		}
		result += "]}";
		session.getTransaction().commit();
		return result;
	}
	
	
	@GET
	@Path("/getByAnswer/{answerID}")
	@Produces(MediaType.TEXT_PLAIN)
	public String getQuestionImgByAnswer(@PathParam("answerID") String answerID){
		Session session = SessionFactoryUtil.getSessionFactory().getCurrentSession();
		 session.beginTransaction();
		List<QuestionImage> list = QuestionImage.getImgOfAnsw(Integer.valueOf(answerID), session);
		String result;
		result = "{QUESTION_IMG:[";
		boolean first = true;
		for (QuestionImage q : list) {
			Integer questImgID = q.getQuestimId();
			Integer questID = q.getQuestion().getQuestionId();
			String questImgLink = q.getQuestimLink();
			result += (first?"":",");
			result += "{";
			first = false;
			result += "\"questImgID\"" + ":\"" + questImgID + "\",";
			result += "\"questID\"" + ":\"" + questID + "\",";
			result += "\"answerID\"" + ":\"" + answerID + "\",";
			result += "\"questImgLink\"" + ":\"" + questImgLink + "\",";
			result += "}";
		}
		result += "]}";
		session.getTransaction().commit();
		return result;
	}
	
	@GET
	@Path("/create/{questID}/{answerID}/{questImgLink}")
	@Produces(MediaType.TEXT_PLAIN)
	public String createQuestionImg(@PathParam("questID") String questID, @PathParam("answerID") String answerID, 
			@PathParam("questImgLink") String questImgLink)
	{
		Session session = SessionFactoryUtil.getSessionFactory().getCurrentSession();
		 session.beginTransaction();
		 try {
			 	QuestionImage q = new QuestionImage();
			 	if(questID.equals("0"))
			 		q.setAnswerItem(AnswerItem.getAnswById(Integer.valueOf(answerID), session));
			 	else
			 		q.setQuestion(Question.getQuestionByID(Integer.valueOf(questID), session));
				q.setQuestimLink(questImgLink);
				session.save(q);
				session.getTransaction().commit();
		} catch (Exception e) {
			// TODO: handle exception
			session.getTransaction().rollback();
			return "error: " + e.getMessage();
		}
		 return "success";
	}
	
	
	@GET
	@Path("/update/{questImgID}/{questID}/{answerID}/{questImgLink}")
	@Produces(MediaType.TEXT_PLAIN)
	public String updateQuestionImg(@PathParam("questImgID") String questImgID,@PathParam("questID") String questID,
			@PathParam("answerID") String answerID,@PathParam("questImgLink") String questImgLink)
	{
		Session session = SessionFactoryUtil.getSessionFactory().getCurrentSession();
		 session.beginTransaction();
		 try {
			 	QuestionImage q = QuestionImage.getQuestImgByID(Integer.valueOf(questImgID), session);
			 	if(questID.equals("0"))
			 		q.setAnswerItem(AnswerItem.getAnswById(Integer.valueOf(answerID), session));
			 	else
			 		q.setQuestion(Question.getQuestionByID(Integer.valueOf(questID), session));
				q.setQuestimLink(questImgLink);
				session.saveOrUpdate(q);
				session.getTransaction().commit();
		} catch (Exception e) {
			// TODO: handle exception
			session.getTransaction().rollback();
			return "error: " + e.getMessage();
		}
		 return "success";
	}
	
	@GET
	@Path("/delete/{questImgID}")
	@Produces(MediaType.TEXT_PLAIN)
	public String deleteQuestionImg(@PathParam("questImgID") String questImgID)
	{
		Session session = SessionFactoryUtil.getSessionFactory().getCurrentSession();
		 session.beginTransaction();
		 try {
			 session.delete(QuestionImage.getQuestImgByID(Integer.valueOf(questImgID), session));
				session.getTransaction().commit();
		} catch (Exception e) {
			// TODO: handle exception
			session.getTransaction().rollback();
			return "error: " + e.getMessage();
		}
		 return "success";
	}
	
	@POST
	@Path("/upload")
	@Consumes(MediaType.MULTIPART_FORM_DATA)
	public String uploadImages(@FormDataParam("file") InputStream uploadInputStream,
			@FormDataParam("file") FormDataContentDisposition fileDetail, @FormDataParam("path") String filePath) {
		String workingDir  = filePath;
		String uploadFileLocation = workingDir + fileDetail.getFileName();
		try {
		//	String workingDir = "D://Temp/";
			File f = new File(".");
			String abso = f.getAbsolutePath();
			System.out.println(abso);
			String ach = f.getCanonicalPath();
			System.out.println(ach);
			String temp = System.getProperty("catalina.home");
			System.out.println(temp);
			writeToFile(uploadInputStream, uploadFileLocation);
		} catch (Exception e) {
			// TODO: handle exception
			return e.getMessage();
		}
		return uploadFileLocation;
		
	}
	
	private void writeToFile(InputStream uploadedInputStream,
			String uploadedFileLocation) throws IOException {
				File f = new File(uploadedFileLocation);
				OutputStream out = new FileOutputStream(f);
				if(!f.exists())
				{
					f.createNewFile();
				}
				int read = 0;
				byte[] bytes = new byte[1024];
	 
				out = new FileOutputStream(new File(uploadedFileLocation));
				while ((read = uploadedInputStream.read(bytes)) != -1) {
					out.write(bytes, 0, read);
				}
				out.flush();
				out.close();
				}
	
}
